<?php
/**
 * The base controller which is used by the Front and the Admin controllers
 */

use EasyWeChat\Foundation\Application;
class Base_Controller extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
        $this->load->database();
        $this->load->model('member_m');
        $this->load->model('message_m');
        if($this->session->userdata('user_id')){
            $data['is_login'] = "1";
            // 用户是否有默认地址
            $dress=$this->member_m->get_adress_by_user_id($this->session->userdata('user_id'));
            if(empty($dress)){
                $data['has_adress'] = '0';
            }else{
                $data['has_adress'] = '1';
            }
        }else{
            $data['is_login'] = "0";
            $data['has_adress'] = '0';
        }
        // 微信授权绑定
        $host = $_SERVER['HTTP_HOST'];
        if(strstr($host, 'wx') && strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            if(empty($this->session->userdata("wechat_user"))){
                $func = !empty($this->router->fetch_method()) ? $this->router->fetch_method() : "index"; // 当前方法名
                if(!in_array($func,["wechatOauthBack"])){
                    $this->oauth(substr($_SERVER['REQUEST_URI'],1));
                }
            }
        }
        $this->load->vars($data);
	}
    /**
     * 微信登录验证
     * @param  string $action 回调的action
     * @return void
     */
    protected function oauth($callbackUrl) {
        // 未登录
        if (!$this->session->has_userdata("wechat_user")) {
            $config = [
                'app_id' => "wx181cba8d8430e3dc",
                'oauth' => [
                    'scopes'   => ['snsapi_base'],
                    'callback' => site_url('home/wechatOauthBack'),
                ],
            ];
            $app = new Application($config);
            $oauth = $app->oauth;
            $this->session->set_userdata('target_url', base_url($callbackUrl));
            $oauth->redirect()->send();
        }
    }
    /**
     * 微信登录验证回调
     * @return void
     */
    public function wechatOauthBack() {

        $config = [
            'app_id' => "wx181cba8d8430e3dc",
            'secret' => "9d086498f63d3a280179f1ca5969c278",
        ];
        $app = new Application($config);
        $oauth = $app->oauth;

        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        $userArr = $user->toArray();
        $this->session->set_userdata('wechat_user', $userArr);
        $this->session->set_userdata('openid', $userArr['id']);
        $targetUrl = empty($this->session->userdata('target_url')) ? '/' : $this->session->userdata('target_url');
        redirect($targetUrl);
    }

    
}
class FOX_Controller extends Base_Controller
{
    public $USER_KEY;
	function __construct(){
		parent::__construct();	
		$data='';
		//判断安装
		$file=FCPATH.'install.lock';
		if (!is_file($file)){
			redirect(site_url('install'));
		}
        $this->load->set_front_theme('wap');
        $this->load->model('member_m');
        $this->load->model('message_m');
		if($this->config->item('site_close')=='off'){
			echo '网站维护关闭中';
			exit;
		}
        // 判断登录
        if(!$this->auth->is_login())
        {
//            redirect(site_url('home/index'));
            redirect(site_url('home/login'));

        }
		$user = array();
        $data = array();
		if($this->session->userdata('user_id')){
			//取一个用户信息
			$user=$this->user_m->get_user_by_user_id($this->session->userdata('user_id'));
			$user['uname']=get_user_name($user['user_name'],$user['user_uname']);
			//获取头像
			$this->load->model('upload_m');
			$user['big_avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'big');
			$user['middle_avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'middle');
			$user['small_avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'small');
		}
        if(isMobile()){
            $this->load->set_front_theme('wap');
            $data['viewmulu']=base_url('public/wap/');
            $data['foot_memu'] = 'home';
            // 用户是否有默认地址
            $dress=$this->member_m->get_adress_by_user_id($this->session->userdata('user_id'));
            if(empty($dress)){
                $data['has_adress'] = '0';
            }else{
                $data['has_adress'] = '1';
            }
            $data['is_login'] = "1";
        }else{
            $this->load->set_front_theme('default');
            $data['viewmulu']=base_url('public/default/');
        }
        $data['user'] = $user;
		$this->load->vars($data);
	}

    /**
     * 创建订单号
     * @return string
     */
    public function create_order_no(){
        $order_number = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        return $order_number;
    }

}

class Admin_Controller extends Base_Controller 
{
	function __construct()
	{
		parent::__construct();
		//载入模板
		$this->load->set_front_theme('manage');
		//判断安装
		$file=FCPATH.'install.lock';
		if (!is_file($file)){
			redirect(site_url('install'));
		}
		// 判断登录
		if(!$this->auth->is_login())
		{
			redirect(site_url("/"));
		}
		$loveme='';
		if($this->session->userdata('user_id')){
			//取一个用户信息
			$data['user']=$this->user_m->get_user_by_user_id($this->session->userdata('user_id'));
			$data['user']['uname']=get_user_name($data['user']['user_name'],$data['user']['user_uname']);
			$data['user']['user_group_name']=$this->user_m->get_user_by_user_group($data['user']['user_group']);
			//获取头像
			$this->load->model('upload_m');
			$data['user']['big_avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'big');
			$data['user']['middle_avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'middle');
			$data['user']['small_avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'small');
		}else{
			$loveme=get_cookie('loveme',TRUE);
			$salt =get_salt();
			if(isset($loveme)){
				if($this->user_m->checklogin($loveme,$salt)){
					redirect(site_url());
				}
			}
		}
		$uid = $this->session->userdata('user_id');
        $con = $this->router->fetch_class(); // 当前控制器
        $func = $this->router->fetch_method(); // 当前方法名
        // 获取当前菜单
        $current = $this->authRule_m->get_current($con,$func);
        if(!isset($current[0])){
            $current = $this->authRule_m->get_current('home','index');
        }
        $data['current']=$current[0];
        $userinfo = $this->user_m->get_user_with_group($uid);
        $menu_access_ids = $userinfo['rules'];
		// 检查访问权限
		$allow_controller_name = array('Upload');//放行控制器名称
        $allow_action_name = array();//放行函数名称
        if ($userinfo['group_id'] != 1 && !$this->auth->check($con . '/' . $func,
                $uid) && !in_array($con, $allow_controller_name) && !in_array($func,
                $allow_action_name)
        ) {
            show_message('没有访问权限',site_url('user/logout'),1);
        }
		// 获取登录用户的权限菜单
        if ($userinfo['group_id'] != 1) {
            $menu_where = "AND id in ($menu_access_ids)";
        } else {
            $menu_where = '';
        }
        $menu = $this->authRule_m->get_menu_by_auth($menu_where);
        $menu = $this->getMenu($menu);
        $data['menu']=$menu;

        // 获取所有的省
        $this->load->model('areas_m');
        $province = $this->areas_m->get_sons_by_pid();
        $data['province']=$province;
	
	 	$data['viewmulu']=base_url('public');
		$data['x_title'] = $this->config->item('site_short_name');
		$this->load->vars($data);
	}

   // 获取菜单
   protected function getMenu($items, $id = 'id', $pid = 'pid', $son = 'children')
    {
        $tree = array();
        $tmpMap = array();
        //修复父类设置islink=0，但是子类仍然显示的bug
        foreach( $items as $item ){
            if( $item['pid']==0 ){
                $father_ids[] = $item['id'];
            }
        }
        //----
        foreach ($items as $item) {
            $tmpMap[$item[$id]] = $item;
        }

        foreach ($items as $item) {
            //修复父类设置islink=0，但是子类仍然显示的bug by shaoneng
            if( $item['pid']<>0 && !in_array( $item['pid'], $father_ids )){
                continue;
            }
            //----
            if (isset($tmpMap[$item[$pid]])) {
                $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
            } else {
                $tree[] = &$tmpMap[$item[$id]];
            }
        }
        return $tree;
    }


}

class Install_Controller extends Base_Controller 
{
	function __construct()
	{
		parent::__construct();
		//载入前台模板
		$this->load->set_front_theme('install');
	}
}

class Test_Controller extends Base_Controller{
	function __construct()
	{
		parent::__construct();
		$this->load->database();
		$data['left_mumen'] = 'messages';
		$this->load->set_front_theme('wap');
		$this->load->vars($data); 
	}

}

class Vip_Controller extends Base_Controller{

    function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->set_front_theme('vip');
        $data['viewmulu']=base_url('public/vip/');
        $data['left_mumen'] = 'messages';
        $data['viewmulu']=base_url('public/vip/');
        // 判断登录
        if(!$this->auth->is_login())
        {
            redirect(site_url("/"));
        }
        //取一个用户信息
        $data['user']=$this->user_m->get_user_by_user_id($this->session->userdata('user_id'));
        $data['user']['uname']=get_user_name($data['user']['user_name'],$data['user']['user_uname']);
        //获取头像
        $this->load->model('upload_m');
        $data['user']['avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'big');
        // 我的订单总数
        // 查询多少订单
        $this->load->model('order_m');
        $data['orders_count'] = $this->order_m->get_shop_orders_count_by_uid($this->session->userdata('user_id'));
        // 最新的通知
        if($this->session->userdata('user_id')){
            $uid = $this->session->userdata('user_id');
            $data['msg'] = $this->message_m->get_new_message($uid);
        }else{
            $data['msg'] = "立即登陆，成为销售合伙人吧！";
        }
        $this->load->vars($data);
    }

}


class Www_Controller extends Base_Controller
{
    protected $cookie_id;

    function __construct()
    {
        parent::__construct();

        //载入模板
        $this->load->set_front_theme('www');
        $data['viewmulu'] = base_url('public/www');
        $func             = $this->router->fetch_method(); // 当前方法名
        $data['func']     = $func;

        $this->load->model('category_m');
        $category         = $this->category_m->get_cates_by_pid(0);
        $data["category"] = $category;

        $this->load->model('zixunCategory_m');
        $zixuncategory         = $this->zixunCategory_m->get_all();
        $data["zixuncategory"] = $zixuncategory;
        // pp($data);exit();
        $this->load->vars($data);
    }
}
